package com.bookstore.action;

import com.bookstore.bean.User;
import com.bookstore.dao.imp.UserDaoImp;
import com.bookstore.service.UserService;
import com.bookstore.dao.UserDAO;
import utils.FormUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;

/**
 * Created by Admin on 2016/8/21.
 */
public class UserAction {
    private UserService userService;

    public void login(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");

        String usernameStr = request.getParameter("username");
        String passwordStr = request.getParameter("password");

       User user = userService.login(usernameStr, passwordStr);
        PrintWriter out = response.getWriter();
        if (user == null) {
            out.print(false);
            response.sendRedirect(request.getContextPath() + "/index.jsp");
        } else {
            out.print(true);
            request.getSession().setAttribute("user", user.getUserName());
            response.sendRedirect(request.getContextPath() + "/book/list");
            return;
        }
    }

    public ModelAndView addUser(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, InvocationTargetException, NoSuchMethodException,
            InstantiationException, IllegalAccessException, NoSuchFieldException {

        User user = (User) FormUtils.parseForm(request, User.class, "utf-8");
        System.out.println(user);
        UserDAO userDAO = new UserDaoImp();
        if (user.getUserName().isEmpty() || user.getPassword().isEmpty()) {
            String str = "请输入完整信息!";
            ModelAndView mv = new ModelAndView("/newuser", ModelAndView.FORWARD);
            mv.addData("message", str);
            return mv;
        } else {
            userDAO.save(user);
            ModelAndView mv = new ModelAndView(request.getContextPath() + "/success1", ModelAndView.REDIRECT);
            return mv;
        }
    }

    public UserService getUserService() {
        return userService;
    }

    public void setUserService(UserService userService) {
        this.userService = userService;
    }
}
